module WindSpirit
{
    //背景图切换轮播封装
    export class TransformBackground extends egret.DisplayObjectContainer
    {
        public bgUrls =
        [
            "http://www.windspirit.cn/weixin/games/resource/bg1.jpg",
            "http://www.windspirit.cn/weixin/games/resource/bg2.jpg",
            "http://www.windspirit.cn/weixin/games/resource/bg3.jpg",
            "http://www.windspirit.cn/weixin/games/resource/bg4.jpg"
        ];
        public bmp: egret.Bitmap;
        public index: number = 0;
        public timer: egret.Timer;
        static textures: egret.Texture[] = [];
        public curIndex = 0;
        public time;
        public constructor(time: number = 3000)
        {
            super();
            this.time = time;
            if(TransformBackground.textures.length == 0)
            {
                this.loadingBgs(0);
            }
            else
            {
                this.start();
            }
        }
        static instance: TransformBackground = null;
        static getInstance(time = 3000)
        {
            if(this.instance == null)
            {
                this.instance = new TransformBackground(time);
            }
            return this.instance;
        }
        public loadingBgs(i)
        {
            RES.getResByUrl(this.bgUrls[i],this.complete,this,RES.ResourceItem.TYPE_IMAGE);
        }
        public start()
        {
            this.bmp = new egret.Bitmap();
            this.setTexture(0);
            this.addChild(this.bmp);
            if(this.bgUrls.length > 1)
            {
                this.timer = new egret.Timer(this.time);
                //this.timer.start();
                this.timer.addEventListener(egret.TimerEvent.TIMER,this.changeBg,this);
            }
        }
        public complete(texture: egret.Texture)
        {
            TransformBackground.textures.push(texture);
            this.curIndex++;
            console.log("load background image" + this.curIndex + "complete");
            if(this.curIndex < this.bgUrls.length)
            {
                this.loadingBgs(this.curIndex);
            }
            else
            {
                this.start();
            }
        }
        public changeBg(event: egret.Event): void
        {
            console.log("change bg");
            this.index++;
            this.index %= this.bgUrls.length;
            var act = egret.Tween.get(this.bmp);
            act.to({ alpha: 0 },500).call(this.transformBg,this);
        }
        public transformBg()
        {
            this.setTexture(this.index);
            var act = egret.Tween.get(this.bmp);
            act.to({ alpha: 1 },500);
        }
        public setTexture(index: number): void
        {
            this.bmp.texture = TransformBackground.textures[index];
            this.bmp.width = WindSpirit.Util.stageW;
            this.bmp.height = WindSpirit.Util.stageH;
        }
    }
}